package com.kc.sys.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.kc.sys.common.*;
import com.kc.sys.domain.Permission;
import com.kc.sys.domain.User;
import com.kc.sys.service.PermissionService;
import com.kc.sys.service.RoleService;
import com.kc.sys.service.UserService;
import com.kc.sys.util.WebUtils;
import com.kc.sys.vo.PermissionVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;

/**
 * <p>
 *  菜单管理前端控制器
 * </p>
 *
 * @author 老杜
 * @since 2019-10-17
 */
@RestController
@RequestMapping("/menu")
public class MenuController {

    @Autowired
    private PermissionService permissionService;
    @Autowired
    private RoleService roleService;
    @Autowired
    private UserService userService;
    @RequestMapping("loadIndexLeftMenu")
    public R loadIndexLeftMenu(PermissionVo permissionVo){
        //查询所有菜单
        QueryWrapper<Permission> queryWrapper = new QueryWrapper<>();
        //设置只能查询菜单
        queryWrapper.eq("type",Constast.TYPE_MENU);
        queryWrapper.eq("available",Constast.AVAILABLE_TRUE);
        User user = (User) WebUtils.getSession().getAttribute("user");
        List<Permission> list = null;
        if (user.getType()==Constast.USER_TYPE_SUPER) {
            list = permissionService.list(queryWrapper);
        }else {
            //用户Id
            Integer uid = user.getId();
            //根据用户Id查询rid
            List<Integer> rids = roleService.queryUserRoleIdsByUid(uid);
            //根据角色Id取到菜单id和权限Id
            Set<Integer> pids = new HashSet<>();
            for (Integer rid : rids) {
                List<Integer> permissionids = roleService.queryRolePermissionIdsByRid(rid);
                pids.addAll(permissionids);
            }
            //根据角色Id查询权限
            if(pids.size()>0){
               queryWrapper.in("id",pids);
                list = permissionService.list(queryWrapper);
            }else {
                list = new ArrayList<>();
            }
            //根据用户ID+角色+权限去查
          //  list = permissionService.list(queryWrapper);
        }
        List<TreeNode> treeNodes=new ArrayList<>();
        for (Permission p : list) {
            Integer id=p.getId();
            Integer pid=p.getPid();
            String title=p.getTitle();
            String icon=p.getIcon();
            String href=p.getHref();
            Boolean spread=p.getOpen()==Constast.OPEN_TRUE?true:false;
            treeNodes.add(new TreeNode(id, pid, title, icon, href, spread));
        }
        System.out.println(list);
        //构造层级关系
        List<TreeNode> list2 = TreeNodeBuilder.build(treeNodes,1);
        return R.ok().data("items",list2);
    }

    /********************************************菜单管理开始********************************************/

    /**
     *加载部门管理左边的部门树结构Json
     */
    @RequestMapping("loadMenuManagerLeftJson")
    public DataGridView loadMenuManagerLeftJson(PermissionVo permissionVo){
        QueryWrapper<Permission> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("type",Constast.TYPE_MENU);
        List<Permission> list = permissionService.list(queryWrapper);
        List<TreeNode> treeNodes = new ArrayList<>();
        for (Permission menu : list) {
            Boolean spread = menu.getOpen()==1?true:false;
            treeNodes.add(new TreeNode(menu.getId(),menu.getPid(),menu.getTitle(),spread));

        }
        return new DataGridView(treeNodes);
    }

    @RequestMapping("loadAllMenu")
    public DataGridView loadAllMenu(PermissionVo permissionVo){

        //获取用户session
        //User user = (User)WebUtils.getSession().getAttribute("user");
        IPage<Permission> page = new Page<>(permissionVo.getPage(),permissionVo.getLimit());
        QueryWrapper<Permission> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(permissionVo.getId()!=null,"id",permissionVo.getId()).or().eq(permissionVo.getId()!=null,"pid",permissionVo.getId());
        queryWrapper.eq("type",Constast.TYPE_MENU);
        queryWrapper.like(StringUtils.isNotBlank(permissionVo.getTitle()),"title",permissionVo.getTitle());
        queryWrapper.orderByAsc("ordernum");
        permissionService.page(page,queryWrapper);
        return new DataGridView(page.getTotal(),page.getRecords());
    }

    //加载最大的排序码
    @RequestMapping("loadMenuMaxOrderNum")
    public Map<String ,Object> loadMenuMaxOrderNum(){
        Map<String,Object> map = new HashMap<>();
        QueryWrapper<Permission> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByDesc("ordernum");
        List<Permission> list = permissionService.list(queryWrapper);
        if(list.size()>0){
            map.put("value",list.get(0).getOrdernum()+1);
        }else{
            map.put("value",1);
        }
        permissionService.list(queryWrapper);

        return map;
    }

    //添加部门
    @RequestMapping("addMenu")
    public R addMenu(PermissionVo permissionVo){
        try {
            permissionVo.setType(Constast.TYPE_MENU);//设置添加类型
            permissionService.save(permissionVo);
            return R.ok().message("添加成功");
        } catch (Exception e) {
            e.printStackTrace();
            return R.error().message("添加失败");
        }
    }

    //更新部门
    @RequestMapping("updateMenu")
    public R updateMenu(PermissionVo permissionVo){
        try {
            permissionService.updateById(permissionVo);
            return R.ok().message("更新成功");
        } catch (Exception e) {
            e.printStackTrace();
            return R.error().message("更新失败");
        }
    }
    /**
     * 根据Id 删除
     * */
    @RequestMapping("deleteMenu")
    public R deleteById(Integer id){
        try {
            permissionService.removeById(id);
            return R.ok().message("删除成功");
        } catch (Exception e) {
            e.printStackTrace();
            return R.error().message("删除失败");
        }
    }

    //检查当前部门有没有子菜单
    @RequestMapping("checkMenuHasChildrenNode")
    public Map<String ,Object> checkMenuHasChildrenNode(PermissionVo permissionVo){
        Map<String,Object> map = new HashMap<>();
        QueryWrapper<Permission> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("pid",permissionVo.getId());
        List<Permission> list = permissionService.list(queryWrapper);
        if(list.size()>0){
            map.put("value",true);
        }else {
            map.put("value",false);
        }
        return map;
    }

    /********************************************菜单管理结束********************************************/

}

